package com.xzy.common.handler;

import com.xzy.common.util.AesUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * AES 数据加密/解密处理器
 *
 * @author xzy.xiao
 * @date 2022/8/4  21:05
 */
public class AesTypeHandler extends BaseTypeHandler<String> {

    private static final Logger logger = LoggerFactory.getLogger(AesTypeHandler.class);

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String columnValue, JdbcType jdbcType) throws SQLException {
        logger.info("AES加密...");
        ps.setString(i, AesUtil.encrypt(columnValue));
    }

    /**
     * Gets the nullable result.
     *
     * @param rs         the rs
     * @param columnName Colunm name, when configuration <code>useColumnLabel</code> is <code>false</code>
     * @return the nullable result
     * @throws SQLException the SQL exception
     */
    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        logger.info("AES解密...");
        String columnValue = rs.getString(columnName);
        return Strings.isBlank(columnValue) ? columnValue : AesUtil.decrypt(columnValue);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        logger.info("AES解密...");
        String columnValue = rs.getString(columnIndex);
        return Strings.isBlank(columnValue) ? columnValue : AesUtil.decrypt(columnValue);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        logger.info("AES解密...");
        String columnValue = cs.getString(columnIndex);
        return Strings.isBlank(columnValue) ? columnValue : AesUtil.decrypt(columnValue);
    }
}
